<template>
  <div class="wrapper-add-edit">
    <el-tabs v-model="tabNameActived">
      <el-tab-pane label="单独添加" name="AddSingle">
        <el-form ref="refForm" :model="formData" :rules="rules" label-width="auto">
          <el-form-item label="所属科室">
            <el-tree-select
              v-model="formData.idDepartment"
              :data="dataTSDepartment"
              :props="{ value: 'id', label: 'label' }"
              :render-after-expand="false"
              :current-node-key="0"
              value-key="id"
              placeholder="选择所属科室"
              check-strictly
              style="width: 300px"
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="mobilePhone">
            <el-col :span="8">
              <el-input
                v-model="formData.mobilePhone"
                placeholder="请输入手机号码..."
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
                show-word-limit
                clearable
              />
            </el-col>
            <el-col :span="16" :push="1">
              <span>手机号码，用于登录系统</span>
            </el-col>
          </el-form-item>

          <el-form-item label="真实姓名" prop="realName">
            <el-col :span="8">
              <el-input v-model="formData.realName" placeholder="请输入真实姓名..." maxlength="10" show-word-limit />
            </el-col>
            <el-col :span="16" :push="1">
              <span>管理员真实姓名</span>
            </el-col>
          </el-form-item>

          <el-form-item label="身份证号" prop="idCard">
            <el-col :span="8">
              <el-input v-model="formData.idCard" placeholder="请输入身份证号码..." maxlength="18" show-word-limit />
            </el-col>
            <el-col :span="16" :push="1">
              <span>管理员身份证号码</span>
            </el-col>
          </el-form-item>

          <el-form-item>
            <el-button type="success" @click="onAdd()">确定添加</el-button>
            <el-button type="info" @click="onBack2List">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="批量添加" name="AddMulti">
        <div class="wrapper-import">
          <a
            class="el-button el-button--success"
            href="/assets/template/roster.xls"
            download="花名册模板.xls"
            target="_blank"
          >
            点此下载花名册Excel模板
          </a>
          <el-button type="primary" icon="Upload">上传花名册批量添加人员</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getAdminId, getAssetsFile } from '@/utils/common'
import { getDefaultConfig } from '@/utils'
import { uuid } from '@/utils/uuid'
import { toastError, toastSuccess } from '@/utils/toast'
import { AryToTree } from '@/utils/array'
import { getLStorageObj } from '@/utils/web-storage'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'AdminAddView',
  components: {},
  setup() {
    const formData = ref({
      id: 0,
      uuid: uuid(true),
      idOpen: '',
      idUnit: 106,
      idDepartment: 106,
      username: '',
      password: '',
      realName: '',
      penName: '',
      gender: '',
      idCard: '',
      mobilePhone: '',
      email: '',
      avatarUrl: '',
      createAdminId: 0,
      dtLastLogin: new Date().getTime(),
      dtCreate: new Date().getTime(),
      enabled: true,
      accountNonExpired: true,
      accountNonLocked: true,
      credentialsNonExpired: true,
      politicalOutlook: '',
      duty: '',
      nation: '',
    })
    const dataTSDepartment = ref([])
    const refForm = ref(null)
    const rules = ref({
      idCard: [{ required: true, message: '请输入身份证号码', trigger: 'blur' }],
      mobilePhone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
      realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    })
    const tabNameActived = ref('AddSingle')
    const templateFile = ref('')

    // 获取当前登录管理员id
    const getIdAdmin = () => {
      formData.value.createAdminId = getAdminId()
    }
    const getDefaultAdminPassword = () => {
      formData.value.password = getDefaultConfig('DefaultAdminPassword')
    }
    const setTemplateFile = () => {
      templateFile.value = getAssetsFile('template/roster.xls')
    }
    const onBack2List = () => {
      router.push({ path: 'list-all' })
    }
    // 得到卫健委下所有科室
    const listDepartment = () => {
      dataTSDepartment.value = AryToTree(getLStorageObj('AllCategory'), 106)
    }
    // 添加管理员
    const onAdd = () => {
      if (!refForm.value) return
      // 如果把 validate() 单独一行，则需要写 async 和 await
      refForm.value.validate((valid) => {
        if (!valid) {
          toastError('表单验证失败！请检查您的输入！')
          return
        }
        // 执行到这里，说明表单验证通过
        store
          .dispatch('sys_admin/add', formData.value)
          .then(() => {
            toastSuccess('添加管理员成功！', 5)
            router.push({ path: 'list-all' })
          })
          .catch((error) => {
            console.log('添加管理员返回错误：', error)
          })
      })
    }

    onMounted(() => {
      getIdAdmin()
      getDefaultAdminPassword()
      setTemplateFile()
      listDepartment()
    })

    return {
      refForm,
      formData,
      rules,
      dataTSDepartment,
      tabNameActived,
      templateFile,

      getIdAdmin,
      getDefaultAdminPassword,
      setTemplateFile,
      listDepartment,
      onBack2List,
      onAdd,
    }
  },
})
</script>

<style lang="scss" scoped></style>
